#include "login.h"

int do_login(clientSession_t *user_session,char *username,char *userpassword)
{
    // 判断用户是否存在
    struct passwd *passwd = getpwnam(username);
    if (passwd == NULL)
    {
        tlv_msg_t msg;
        bzero(&msg, sizeof(msg));
        char value[] = "username error!";
        msg.hdr.length = strlen(value);
        tlv_create(&msg, LOGIN_FALSE, msg.hdr.length, value);
        tlv_send(user_session->netfd, &msg);
        printf("用户不存在.\n");
        return -1;
    }

    // 根据用户名获取密文密码放在encrypted
    char encrypted[1024] = {0};
    struct spwd *userinfo = getspnam(username);
    if (userinfo == NULL)
    {
        perror("getspnam");
        return -1;
    }
    strcpy(encrypted, userinfo->sp_pwdp);
    // printf("%s\n",encrypted);

    // 提取密文的盐值
    char salt[1024] = {0};
    char *pfirst_dollor = strchr(encrypted, '$');
    char *plast_dollor = strrchr(encrypted, '$');
    if (pfirst_dollor != NULL && plast_dollor != NULL && pfirst_dollor != plast_dollor)
    {
        int length = plast_dollor - pfirst_dollor;
        memcpy(salt, encrypted, length + 1);
    }
    // printf("%s\n",salt);

    // 根据明文密码和盐值得到密文
    char password[1024] = {0};
    strcpy(password, userpassword);
    char crypt_password[1024] = {0};
    const char *crypt_result=crypt(password, salt);
    if(crypt_result)
    {
        strcpy(crypt_password, crypt_result);
    }
    // printf("%s\n",crypt_password);

    // 将生成的密文和存在系统中的密文进行对比
    if (strcmp(crypt_password, encrypted) == 0)
    {
        tlv_msg_t msg;
        bzero(&msg, sizeof(msg));
        char value[] = "login success!";
        msg.hdr.length = strlen(value);
        tlv_create(&msg, LOGIN_IN, msg.hdr.length, value);
        tlv_send(user_session->netfd, &msg);
        printf("验证成功.\n");
        return 0;
    }
    else
    {
        tlv_msg_t msg;
        bzero(&msg, sizeof(msg));
        char value[] = "userpassword error!";
        msg.hdr.length = strlen(value);
        tlv_create(&msg, LOGIN_FALSE, msg.hdr.length, value);
        tlv_send(user_session->netfd, &msg);
        printf("验证失败.\n");
        return -1;
    }
}
